package net.jforum.repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.jforum.cache.CacheEngine;
import net.jforum.cache.Cacheable;
import net.jforum.dao.DataAccessDriver;
import net.jforum.dao.SummaryDAO;
import net.jforum.entities.Topic;
import net.jforum.util.CommonUtil;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.log4j.Logger;

/**
 * @ author  张洋 jackson.zhang@ericsson.com
 * @ version 创建时间 ：Sep 27, 2010  12:41:11 AM
 * @ description : 
 */
public class SummaryRepository implements Cacheable{
	private static Logger logger = Logger.getLogger(SummaryRepository.class);
	private static CacheEngine cache;
	
	private static String FQN="summary";
	
	private static String DAILY_FORUM_TOPIC=FQN+"daily_forum_topic";//(DAILY_FORUM_TOPIC,(forumId,count))
	
	private static String DAILY_ALL_TOPIC=FQN+"daily_all_topic";
	
	private static String WEEKLY__TOPICS_By_REPLIES=FQN+"weekly_by_replies";
	
	private static String WEEKLY_TOPICS_BY_VIEWS=FQN+"weekly_hot_by_views";
	
	private static String MONTHLY_TOPICS_BY_REPLIES=FQN+"monthly_by_replies";
	
	private static String MONTHLY_TOPICS_BY_VIEWS="FQN"+"monthly_by_views";
	
	public void setCacheEngine(CacheEngine engine) {
		 cache = engine;
	}
	public static void  initLoad(){
		loadCountTodayTopicsAll();//每个版块forum
		loadAllNewTopicCountToday();//虚拟总论坛
		loadWeeklyTopicsByViewsByLimit();
		
	}
 
	
	public static int loadCountTodayTopicsByForum(int forumId){
		return 0;
	}
	
	public static void pushTopic(int forumId){
		increaseTodayTopicCountByForum(forumId,1);
		increaseCounttAllNewTopicToday(1);
	}
	
	public static void clearCountTodayTopicsAll(){
		synchronized(DAILY_FORUM_TOPIC){
			cache.add(DAILY_FORUM_TOPIC, new HashMap());
		}
	}
	
	//从数据库load出所有的forum对应的发帖数
    
	public static Map loadCountTodayTopicsAll(){
		if(logger.isDebugEnabled()){
			logger.debug("loading CountTodayTopicsAll......");
		}
		Date startDate=new Date();
		startDate.setHours(0);
		startDate.setMinutes(0);
		startDate.setSeconds(0);
		System.out.println(startDate);
		Date endDate=new Date();
		endDate.setHours(endDate.getHours()+1);
		Map  result=new HashMap();
		synchronized(DAILY_FORUM_TOPIC){//其实可以是悲观锁，get set不一致没有关系
		  SummaryDAO summaryDao=DataAccessDriver.getInstance().newSummaryDAO();

		  result=summaryDao.countTopicWithForumIdsByTimeLimit(startDate, endDate);
			cache.add(DAILY_FORUM_TOPIC,result);
		}
		return result;
	}
	//根据forumId来获取当天该forum的发帖数
	public  static int getCountTodayByForumId(int forumId){
		 
			Integer count=(Integer)cache.get(DAILY_FORUM_TOPIC,Integer.toString(forumId));
			if(count!=null){
				return count.intValue();
			}
			return 0;
	
	}
	// 增加某个forum当天的发帖数
	public static void  increaseTodayTopicCountByForum(int forumId,int num){
		synchronized(DAILY_FORUM_TOPIC){
			Integer count=(Integer)cache.get(DAILY_FORUM_TOPIC,Integer.toString(forumId));
			if(count==null){
				count=0;
			}
			logger.debug("increateTodayTopicCountByForum,count="+count+num);
		    cache.add(DAILY_FORUM_TOPIC, Integer.toString(forumId),count+num);
			 
		}
		
	}
	public static void  decreaseTodayTopicCountByForum(int forumId,int num){
		synchronized(DAILY_FORUM_TOPIC){
			Integer count=(Integer)cache.get(DAILY_FORUM_TOPIC,Integer.toString(forumId));
			if(count==null){
				count=0;
			}
			logger.debug("increateTodayTopicCountByForum,count="+(count-num));
		    cache.add(DAILY_FORUM_TOPIC, Integer.toString(forumId),count-num);
			 
		}
		
	}
	
	
	//load虚拟总论坛中的当日发帖数
	public static int loadAllNewTopicCountToday(){
		if(logger.isDebugEnabled()){
			logger.debug("loading loadcountAllForumTodayTopic......");
		}
		Date startDate=CommonUtil.getTodayMorning(new Date());
		System.out.println(startDate);
		Date endDate=new Date();
		endDate.setHours(endDate.getHours()+1);
		 int result=0;
		synchronized(DAILY_ALL_TOPIC){//其实可以是悲观锁，get set不一致没有关系
		  SummaryDAO summaryDao=DataAccessDriver.getInstance().newSummaryDAO();

		  result=summaryDao.countTopicsAllByTimeLimit(startDate, endDate);
		  cache.add(DAILY_ALL_TOPIC,result);
		}
		return result;
	}
	
	//
	public static int getAllNewTopicCountToday(){
	 
			Integer count=(Integer)cache.get(DAILY_ALL_TOPIC);
			if(count!=null){
				return count.intValue();
			}
			return 0;
		 
	}
	public static void  increaseCounttAllNewTopicToday(int num){
		synchronized(DAILY_ALL_TOPIC){
			Integer count=(Integer)cache.get(DAILY_ALL_TOPIC);
			if(count==null){
				count=0;
			}
			logger.debug("increateCounttAllNewTopicToday,count="+(count+num));
		    cache.add(DAILY_ALL_TOPIC, count+num);
		}
		
	}
	public static  void  decreaseCounttAllNewTopicToday(int num){
		synchronized(DAILY_ALL_TOPIC){
			Integer count=(Integer)cache.get(DAILY_ALL_TOPIC);
			if(count==null){
				count=0;
			}
			logger.debug("increateCounttAllNewTopicToday,count="+(count-num));
		    cache.add(DAILY_ALL_TOPIC, count-num);
		}
		
	}
	
	public static  void clearCounttAllNewTopicToday(){
		synchronized(DAILY_ALL_TOPIC){
			cache.add(DAILY_ALL_TOPIC, 0);
		}
	}
	
	/*
	 * 
	 * weekly summary
	 * 
	 */
	public static boolean isTopicInWeeklyRepliesSummary(Topic topic){
		List topics=(List)cache.get(WEEKLY__TOPICS_By_REPLIES);
		int index=topics.indexOf(topic);
        return index>-1?true:false;
	}
	public static  List loadWeeklyTopicsByRepliesByLimit(int limit){
		if(logger.isDebugEnabled()){
			logger.debug("start loadWeeklyTopicsByRepliesByLimit...");
		}
		Date endDate=new Date();
		Date startDate=CommonUtil.getDateWeekBefore(endDate);
		List topics=new ArrayList();
		synchronized(WEEKLY__TOPICS_By_REPLIES){//其实可以是悲观锁，get set不一致没有关系
			  SummaryDAO summaryDao=DataAccessDriver.getInstance().newSummaryDAO();
			   topics=summaryDao.topicsByRepliesByTimeLimit(startDate, endDate, limit);
			   cache.add(WEEKLY__TOPICS_By_REPLIES, topics);
			  }
		
		return topics;
	}
	
	
	public static boolean isTopicInWeeklyViewsSummary(Topic topic){
		List topics=(List)cache.get(WEEKLY_TOPICS_BY_VIEWS);
		int index=topics.indexOf(topic);
        return index>-1?true:false;
	}
	public static List loadWeeklyTopicsByViewsByLimit(){
		
		Date endDate=new Date();
		Date startDate=CommonUtil.getDateWeekBefore(endDate);
		List topics=new ArrayList();
		int limit =SystemGlobals.getIntValue(ConfigKeys.WEEKLY_SUMMARY_TOPICS_CACHE_SIZE);
		if(logger.isDebugEnabled()){
			logger.debug("start loadWeeklyTopicsByViewByLimit..."+"startDate:"+startDate+" ; endDate : "+endDate);
		}
		synchronized(WEEKLY_TOPICS_BY_VIEWS){//其实可以是悲观锁，get set不一致没有关系
			  SummaryDAO summaryDao=DataAccessDriver.getInstance().newSummaryDAO();
			   topics=summaryDao.topicsByViewsByTimeLimit(startDate, endDate, limit);
			   cache.add(WEEKLY_TOPICS_BY_VIEWS, topics);
			  }
		return topics;
	}
	
	 public static List getCachedWeeklyTopicsByViewsByLimit(){
		List cachedTopics=(List)cache.get(WEEKLY_TOPICS_BY_VIEWS);
        return cachedTopics!=null?cachedTopics:loadWeeklyTopicsByViewsByLimit();
	}
    
	 public static List getWeeklyTopicsByViewsByLimist(int limit){	 
		List list= getCachedWeeklyTopicsByViewsByLimit();
        if(limit>=list.size()) return list;
        else{
        	return list.subList(0, limit);
        }
	 }
	/*
	 * 
	 * 
	 * montyly summary
	 */
	public static synchronized List loadMonthlyTopicsByRepliesByLimit(int limit){
		if(logger.isDebugEnabled()){
			logger.debug("start loadMonthlyTopicsByRepliesByLimit...");
		}
		Date endDate=new Date();
		Date startDate=CommonUtil.getDateMonthlyBefore(endDate);
		List topics=new ArrayList();
		synchronized(MONTHLY_TOPICS_BY_REPLIES){//其实可以是悲观锁，get set不一致没有关系
			  SummaryDAO summaryDao=DataAccessDriver.getInstance().newSummaryDAO();
			   topics=summaryDao.topicsByRepliesByTimeLimit(startDate, endDate, limit);
			  }
		return topics;
	}
	
	public static boolean isTopicInMonthlyRepliesSummary(Topic topic){
		List topics=(List)cache.get(MONTHLY_TOPICS_BY_REPLIES);
		int index=topics.indexOf(topic);
		return index>-1?true:false;
	}
	 

}
